package glassline;

import transducer.TChannel;
import transducer.TEvent;
import transducer.TReceiver;

public class ShuttleAgent extends FactoryAgent implements TReceiver {
	public ShuttleAgent(int componentNumber) {
		super(componentNumber);
		
		// Register channel with the transducer
		Factory.transducer.register(this, TChannel.SHUTTLE);
	}
	
	public class MyGlass {
		Glass g;
		public boolean done = false;
		
		public MyGlass(Glass g) {
			this.g = g;
		}
	}
	public MyGlass currentGlass = null;
	
	// Messages
	/* (non-Javadoc)
	 * @see glassline.Cutter#msgHereIsGlass(glassline.Glass)
	 */
	@Override
	public void msgHereIsGlass(Glass g) {
		if (currentGlass != null) {
			System.out.println("ERROR: Inline components can't hold 2 pieces of glass!");
		}
		
		print("Component received " + g + "!");
		
		previousComponent.msgIHaveSpaceAvailable(false);
		currentGlass = new MyGlass(g);
	}
	
	@Override
	public void msgIHaveSpaceAvailable(boolean spaceAvailable) {
		print("Shuttle " + componentNumber + "just got msgIHaveSpaceAvailable(" + spaceAvailable + ")");
		nextComponent.spaceAvailable = spaceAvailable;
		stateChanged();
	}

	/* (non-Javadoc)
	 * @see glassline.Cutter#pickAndExecuteAnAction()
	 */
	@Override
	public boolean pickAndExecuteAnAction() {
		// Rule #1
		if (on && !nextSpaceAvailable()) {
			stop();
			return true;
		}
		else if (!on && nextSpaceAvailable()) {
			start();
			return true;
		}
		return false;
	}
	
	// Transducer event listener.
	/* (non-Javadoc)
	 * @see glassline.Cutter#eventFired(transducer.TChannel, transducer.TEvent, java.lang.Object[])
	 */
	public void eventFired(TChannel channel, TEvent event, Object[] args) {
		if (channel == TChannel.SHUTTLE) {
			if (event == TEvent.SHUTTLE_GUI_RELEASED) {
				if ((Integer)args[0] == componentNumber) {
					print("shuttle next component " + componentNumber);
					nextComponent.component.msgHereIsGlass(currentGlass.g);
					currentGlass = null;
					previousComponent.msgIHaveSpaceAvailable(true);
				}
			}
		}
	}
	
	// Actions
	public void start() {
		Factory.transducer.fireEvent(TChannel.SHUTTLE, TEvent.SHUTTLE_DO_START, null);
		on = true;
	}
	
	public void stop() {
		Factory.transducer.fireEvent(TChannel.SHUTTLE, TEvent.SHUTTLE_DO_STOP, null);
		on = false;
	}
}
